import render_content from "./render_content.mjs";
import {
  nearest_data,
  nearest_datacontainer,
  nearest_formview,
  nearest_render,
} from "./nearest.mjs";
import datarover from "./datarover.mjs";
import collectdata, { collectfile } from "./collectdata.mjs";

import { clearafterqueue } from "./delay_render.mjs";

/**
 * 渲染辅助函数 - 用于处理DOM元素的属性、样式、数据绑定和事件
 * @param {HTMLElement} element - 需要处理的DOM元素
 * @param {Object} template - 包含元素配置的模板对象
 */
export default function (element, template) {
  // 设置基本属性：name、id、class
  if (template.name !== undefined) {
    element.setAttribute("name", template.name);
  }
  if (template.id !== undefined) {
    element.setAttribute("id", template.id);
  }

  // 设置元素样式
  if (template.style) {
    if (typeof template.style === "string") {
      element.style = template.style;
    } else {
      Object.keys(template.style).forEach(function (key) {
        if (typeof template.style[key] === "function") {
          element.style.setProperty(
            key,
            template.style[key]({
              container: element,
              data: nearest_data(element),
            })
          );
        } else {
          element.style.setProperty(key, template.style[key]);
        }
      });
    }
  }

  // 处理class属性，支持函数或字符串形式
  if (template.class !== undefined) {
    let _class;
    if (typeof template.class === "function") {
      _class = template.class(element, template, nearest_data(element));
    } else {
      _class = template.class;
    }
    _class?.split(" ").forEach((c) => {
      element.classList.add(c);
    });
  }

  // 设置元素尺寸：width和height
  if (template.width) {
    element.style.setProperty(
      "width",
      typeof template.width === "number"
        ? template.width + "px"
        : template.width
    );
  }
  if (template.height) {
    if (template.height === "auto") {
      // console.log({ element, height: template.height });
      element.style.setProperty(
        "height",
        `calc(100% - ${element.offsetTop}px)`
      );
    } else
      element.style.setProperty(
        "height",
        typeof template.height === "number"
          ? template.height + "px"
          : template.height
      );
  }

  // 设置元素类型
  if (template.type) {
    element.setAttribute("type", template.type);
  }

  // 处理元素属性设置
  let attr;
  if (element.nodeName === "A") {
    attr = template.attr;
  } else {
    attr = template.a;
  }
  if (attr !== undefined) {
    Object.keys(attr).forEach(function (key) {
      if (typeof attr[key] === "function") {
        element.setAttribute(
          key,
          attr[key]({
            container: element,
            data: nearest_data(element),
          })
        );
      } else {
        if (attr[key] !== undefined)
          if (typeof attr[key] === "string")
            element.setAttribute(key, render_content(element, attr[key]));
          else element.setAttribute(key, attr[key]);
      }
    });
  }

  // 处理数据双向绑定
  if (template.bind) {
    let value = datarover(element, template.bind);

    // 根据不同的元素类型设置值
    switch (element.nodeName.toLowerCase()) {
      case "input":
        if (element.getAttribute("type") === "checkbox") {
          element.checked = value;
        } else if (element.getAttribute("type") === "file") {
          console.log({ element, value });
          element.org_data = Array.isArray(value) ? value : [];
          render_filelist(element, element.org_data);
        } else {
          element.value = value || "";
        }
        break;
      case "select":
      case "textarea":
        element.value = value || "";
        break;
      default:
        if (element.set) {
          element.set(value);
        } else element.innerText = value || "";
        break;
    }

    // 监听change事件实现双向绑定
    element.addEventListener("change", (ev) => {
      if (
        element.nodeName.toLowerCase() === "input" &&
        element.getAttribute("type") === "checkbox"
      ) {
        datarover(element, template.bind, element.checked);
      } else if (
        element.nodeName.toLowerCase() === "input" &&
        element.getAttribute("type") === "file"
      ) {
        console.log({ element, value: element.value });
        let obj = Object.fromEntries(element.org_data.map((v) => [v.name, v]));
        console.log({ obj, files: element.files });
        for (let i = 0; i < element.files.length; i++) {
          let v = element.files[i];
          console.log({ v });
          obj[v.name] = {
            name: v.name,
            size: v.size,
            type: v.type,
            lastModified: v.lastModified,
          };
        }
        // let value = Array.from(element.files, (v, k) => {
        //   console.log({ v, k });
        //   return {
        //     name: v.name,
        //     size: v.size,
        //     type: v.type,
        //     lastModified: v.lastModified,
        //   };
        // });
        let value = Object.values(obj);
        console.log({ value, obj });
        render_filelist(element, value);
        // element.new_data = value;
        datarover(element, template.bind, value);
      } else {
        datarover(element, template.bind, element.value?.trim());
      }
      clearafterqueue();
    });

    if (template.afterbind) template.afterbind(element);
  } else {
    // 处理单向数据绑定
    if (template.value) {
      element.value = render_content(element, template.value);
    }
  }

  // 绑定自定义事件
  if (template.event) {
    for (let key in template.event) {
      element.addEventListener(
        key,
        (ev) => {
          template.event[key]({
            sender: element,
            org_data: nearest_data(element),
            new_data: collectdata(nearest_datacontainer(element)),
            value: element.value,
            event: ev,
          });
        },
        false
      );
    }
  }

  // 处理点击事件绑定
  if (template.click) {
    element.classList.add("click");
    element.addEventListener(
      "click",
      function (e) {
        let datacontainer = nearest_datacontainer(this);
        // console.log({ this: this, datacontainer });
        let new_data = collectdata(datacontainer);

        // 构造事件参数对象
        let para = {
          sender: this,
          org_data: nearest_data(this),
          new_data: new_data,
          rowindex: datacontainer ? datacontainer.thin_rowindex : 0,
          event: e,
        };

        let new_file = collectfile(datacontainer);
        // console.log({ new_file });
        if (Object.keys(new_file).length > 0) {
          para.new_file = new_file;
        }

        // 特殊处理button元素的点击状态
        switch (element.nodeName) {
          case "BUTTON":
            element.disabled = true;
            para.done = function () {
              element.disabled = false;
            };
            break;
          default:
            break;
        }

        // 获取表格相关数据
        let tb = this.closest("tbody");
        if (tb?.thin_data) para.group_data = tb.thin_data;

        // 处理表单视图模式切换
        let formview = nearest_formview(this);
        if (formview) {
          para.editmode = function () {
            formview.thin_viewmode = "edit";
            formview.thin_render();
          };
          para.readmode = function () {
            formview.thin_viewmode = "read";
            formview.thin_render();
          };
        }

        // 添加重新渲染方法
        para.rerender = function () {
          let ajax = element.closest("ajax");
          if (ajax) {
            ajax.thin_render();
          } else {
            nearest_render(element)?.thin_render();
          }
        };

        // 执行点击回调
        template.click(para);
      },
      false
    );
  }

  function render_filelist(input, value) {
    console.log({ input, value });
    let files = input.closest("files");
    let list = files.querySelector("list");
    list.innerHTML = "";

    value?.forEach((v) => {
      let item = document.createElement("div");
      item.innerHTML = v.name;
      list.appendChild(item);
    });
  }
}
